<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // https://juejin.cn/post/7037078362417791007#heading-1
        const arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4},
]

const obj = {
  id: 1,
  name: "部门1",
  pid: 0,
  children: [
    {
      id: 2,
      name: "部门2",
      pid: 1,
      children: []
    },
    {
      id: 3,
      name: "部门3",
      pid: 1,
      children: [
        {
          id: 4,
          name: "部门4",
          pid: 3,
          children: [
            {
              id: 5,
              name: "部门5",
              pid:4,
              children: []
            }
          ]
        }
      ]
    }
  ]
}

        /**
 * @param {arr: array 原数组数组, id: number 父节点id} 
 * @return {children: array 子数组}
 */
        function getChildren(arr, id) {
            const res = [];
            for (const item of arr) {
                console.log('item.pid',item.pid);
                console.log('id',id);
                if (item.pid === id) { // 找到当前id的子元素
                    // 插入子元素，每个子元素的children通过回调生成
                    res.push({ ...item, children: getChildren(arr, item.id) });
                }
            }
            return res;
        }

        let res=getChildren(arr, 0);
        console.log(res);

    </script>
</body>

</html>